"""
处理所有文件相关的操作
"""

import xlrd
import warnings
import yaml
from conf import settings

class FileOperator(object):

	def __init__(self, file_path, sheet_by_index=0, key='dict', type='excel'):
		self.file_path = file_path
		self.sheet_by_index = sheet_by_index
		self.key = key
		self.type = type
	def _get_excel(self):
		with warnings.catch_warnings():
			warnings.filterwarnings('ignore', category=PendingDeprecationWarning)
			warnings.filterwarnings('ignore', category=DeprecationWarning)
			book_obj = xlrd.open_workbook(self.file_path)

			sheet_obj = book_obj.sheet_by_index(self.sheet_by_index)
			# 获取title
			title = sheet_obj.row_values(0)
			if self.key == 'list':
				return [dict(zip(title, sheet_obj.row_values(row))) for row in range(1, sheet_obj.nrows)]
			else:
				d = {}
				for row in range(1, sheet_obj.nrows):
					tmp_d = dict(zip(title, sheet_obj.row_values(row)))
					# print(tmp_d['case_num'])
					d[tmp_d['case_num']] = tmp_d
				return d

	def _get_yaml(self):
		""" 获取yaml文件类型的用例 """
		with open(self.file_path, 'r', encoding='utf-8') as f:
			data = yaml.load(f, yaml.FullLoader)
			if self.key == 'dict':
				return data
			else:
				return [value for value in data.values()]

	def _get_mysql(self):
		return '从MySQL数据库取文件'

	def _get_mongodb(self):
		return '从mongodb数据库取文件'

	def get_data(self):
		if hasattr(self, '_get_{}'.format(self.type)):
			return getattr(self,'_get_{}'.format(self.type))()
		else:
			print('不支持的文件读取类型')

if __name__ == '__main__':
    obj = FileOperator(settings.EXCLE_FILE_PATH, type='excel', sheet_by_index=1)
    data = obj.get_data()
    print(data)











